/**
 @author: zhulizhe
 @date: 2020-05-21 00:44:24
 @Email：345841634@qq.com
 @url：https://github.com/lovecrossyou
 */
import React, {useState, useEffect, useRef} from 'react';
import {Text, View, StyleSheet, TouchableOpacity, ScrollView, Image, StatusBar} from 'react-native';
import VideoPlayer from 'react-native-video-player';
import {checkUpdate, req_course, req_execise} from '@/util/apis';
import {height, scaleSizeH, scaleSizeW, width} from '@/util/screen';
import LoadingUtil from '@/util/loading';
import Modal from 'react-native-modalbox';
import Video from 'react-native-video';
import SafeAreaView from 'react-native-safe-area-view';

// const default_url = 'http://qnimage.xiteng.com/2020-08-01%20015457.mov';
const default_url = 'http://qnimage.xiteng.com/2019Commerical.mp4';
const video_cover = `${default_url}?vframe/jpg/offset/0`;

function ClassDetail(props) {
    const {navigation, route} = props;
    const [list, setData] = useState([]);
    const [video_url, setUrl] = useState(default_url);
    const [muted, setMute] = useState(true);
    const [paused, setPause] = useState(false);
    const videoPlayerRef = useRef();
    const modalRef = useRef();
    const [isModalVisible, setModalVisible] = useState(false);
    const id = route.params.item.id;
    console.log('item', route.params.item);
    const req_class = async () => {
        LoadingUtil.startShowLoading();
        const res = await req_course(id);
        if (res.courseExercises) {
            console.log('res ', res);
            setData(res.courseExercises);
        }
        LoadingUtil.dismissLoading();
    };

    /**
     * 播放
     */
    const playVideo = () => {
        setPause(false);
        seek(0);
    };

    const seek = (second = 0) => {
        videoPlayerRef.current.seek(second);
    };

    /**
     * 暂停
     */
    const pauseVideo = () => {
        setPause(true);
    };

    const showModal = () => {
        modalRef.current.open();
    };

    const closeModal = () => {
        modalRef.current.close();
    };

    /**
     * 列表点击
     * @param exercise
     * @returns {Promise<void>}
     */
    const loadVideo = async (exercise) => {
        console.log('exercise#####', exercise);
        const res = await req_execise(exercise.courseDetailId);
        if (res.success === true) {
            console.log('req_execise001', res);
            // pauseVideo();
            setUrl(res.url);
            // setUrl(default_url);
            playVideo();
            closeModal();
        }
    };

    useEffect(() => {
        req_class();
        navigation.setOptions({
            title: route.params.item.courseCategoryName.toUpperCase(),
        });
    }, []);
    return (
        <SafeAreaView style={styles.container}>
            <StatusBar translucent={true} backgroundColor="#000000" />
            {/*播放器*/}
            {video_url ? (<Video
                poster={video_cover}
                resizeMode={'contain'}
                controls={true}
                // maxBitRate={30000}
                source={{uri: video_url}}   // Can be a URL or a local file.
                ref={videoPlayerRef}
                paused={paused}
                minLoadRetryCount={5}
                style={styles.backgroundVideo}/>) : null}
            {/*顶部按钮*/}
            <TouchableOpacity style={styles.top_menu_btn_box} onPress={showModal}>
                <Image style={styles.drop_down_icon} source={require('@/images/drop_down.png')}/>
            </TouchableOpacity>

            {/*课程选择*/}
            <Modal
                style={styles.play_lists}
                position={'top'}
                entry={'top'}
                ref={modalRef}
                isOpen={isModalVisible}>
                <ScrollView>
                    <View>
                        {list.map((data, index) => (
                            <TouchableOpacity onPress={() => loadVideo(data)} key={`${index}#`} style={styles.execise}>
                                <Text>{data.exercise}</Text>
                                <Text>{`${data.exerciseDuration}m`}</Text>
                            </TouchableOpacity>))}
                    </View>
                </ScrollView>
            </Modal>
        </SafeAreaView>
    );
}

const styles = StyleSheet.create({
    execise: {
        display: 'flex',
        flexDirection: 'row',
        justifyContent: 'space-between',
        alignItems: 'center',
        height: scaleSizeH(120),
        borderWidth: scaleSizeH(1),
        borderColor: '#f9f9f9',
        paddingHorizontal: scaleSizeW(40),
    },
    backgroundVideo: {
        position: 'absolute',
        top: 0,
        left: 0,
        bottom: 0,
        right: 0,
    },
    container: {
        flex: 1,
        alignItems: 'center',
        backgroundColor: '#000000',
        display: 'flex',
        flexDirection: 'column',
        width: '100%',
        position: 'relative',
    },
    top_menu_btn_box: {
        position: 'absolute',
        top: 0,
        left: 0,
        right: 0,
        height: scaleSizeH(60),
        justifyContent: 'center',
        flexDirection: 'column',
        alignItems: 'center',
        backgroundColor: '#000',
    },
    top_menu_btn: {
        height: scaleSizeH(60),
        width: scaleSizeW(80),
    },
    drop_down_icon: {
        width: scaleSizeW(352 * 0.2),
        height: scaleSizeW(200 * 0.2),
    },
    play_box: {
        backgroundColor: '#333333',
        width: '100%',
    },
    play_lists: {
        backgroundColor: '#fff',
        width: '100%',
        maxHeight: height * 0.5,
        paddingTop: scaleSizeH(60)
    },
});

export default ClassDetail;
